package com.t18;

import java.io.*;

/**
 * Created by xuyiwei on 2018/9/5.
 */
public class SerialCtl implements Serializable{
    private String a;
    private transient String b;
    public SerialCtl(String a, String b) {
        this.a = a;
        this.b = b;
    }
    @Override
    public String toString() {
        return "SerialCtl{" + "a='" + a + '\'' +  ", b='" + b + '\'' +  '}';
    }
    private void writeObject(ObjectOutputStream out) throws IOException {
        out.defaultWriteObject();
        out.writeObject(b);
    }
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        //本来transient是不放进序列化的  自定义的read和write都是把b写进去
        b = (String)in.readObject();
    }
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        SerialCtl sc = new SerialCtl("Test1","Test2");
        System.out.println("Before:\n"+sc);
        ByteArrayOutputStream buff = new ByteArrayOutputStream();
        ObjectOutputStream o = new ObjectOutputStream(buff);
        //把序列化信息写进字节缓冲区
        o.writeObject(sc);
        //从字节缓冲区读取
        ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buff.toByteArray()));
        SerialCtl sc2 = (SerialCtl) in.readObject();
        System.out.println(sc2);
        /**
         * Before:
         SerialCtl{a='Test1', b='Test2'}
         SerialCtl{a='Test1', b='Test2'}
         */
    }

}
